package com.sinosoft.sinopay.apiservise.chinapay.util;

import chinapay.Base64;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;


/**
 * 【接口支付工具类】
 * @Description: 接口支付工具类
 * @author liuyjsh@sinosoft.com.cn
 * @date 2016年5月26日 下午8:20:54 
 * @version V1.0
 */
public class PaymentUtil {
    
    public static String sign(String data){return "";}

    public static void main(String[] args) {
        checkKeyd("abcdsdfasdf","808080211388326");
    }
	/** 
	 * 上银联秘钥生成
	 * @Title: checkKeyd 
	 * @param plainData
	 * @param MerId
	 * @return
	 */
	public static String checkKeyd(String plainData,String MerId){
		//初始化key文件	
		chinapay.PrivateKey key=new chinapay.PrivateKey();
		chinapay.SecureLink t;
		boolean flag;
		
		String chkValue2;
//		String url= getUrl(getConfig("MerPrk.key","config.properties")).toString().replace("file:", "");
//		url=getKeyPath("MerPrk.key");
		
		String url="config/chinapay/MerPrK_uat.key";
		flag=key.buildKey(MerId,0,url);
		//flag=key.buildKey(MerId,0,getPath(getConfig("MerPrk.key","config.properties")).toString().replace("file:", ""));
		if (flag==false)
		{
		System.out.println("build key error!!1111");
		return null;
		}
		t=new chinapay.SecureLink (key);
		// 对一段字符串的签名
		
		String plainDataBase64 = new String(Base64.encode(plainData.toString().getBytes()));
		chkValue2 = t.Sign(plainDataBase64) ; //
		return chkValue2;
		
	}
	
    private static String getKeyPath(String keyName) {
        String path = ChinapaySignUtil.class.getClassLoader().getResource("/").toString();
        path = path.replaceAll("file:/", "");
        path += "config/chinapay/"+keyName;
        return path;
    }
	/**
	 * 
	 * 获取配置文件路径
	 * @Title: getUrl 
	 * @Description: 获取配置文件路径
	 * @param fileName
	 * @return
	 */
	private static URL getUrl(String fileName){
		return PaymentUtil.class.getClassLoader().getResource("config/chinapay/" + fileName);
	}

	/**
	 * 
	 * 读取配置文件
	 * @Title: getConfig 
	 * @Description: 读取配置文件
	 * @param key
	 * @param fileName
	 * @return
	 */
	private static String getConfig(String key, String fileName) {
		PropertyFileUtils.init(PaymentUtil.class.getClassLoader().getResource("config/chinapay/" + fileName));
		return PropertyFileUtils.getConfig(key);
	}

	/**
	 * 
	 * 上银联验证秘钥
	 * @Title: checkkey 
	 * @Description: TODO
	 * @param ChkValue2
	 * @param plainData
	 * @return
	 */
	public static boolean checkkey(String ChkValue2,String plainData){
		
		chinapay.PrivateKey key=new chinapay.PrivateKey();
		chinapay.SecureLink t;
		boolean flag;
		boolean flag1;
		flag=key.buildKey("999999999999999",0,getUrl(getConfig("PgPubk.key","config.properties")).toString().replace("file:", ""));
		if (flag==false)
		{
		String msg="build key error!";
		System.out.println(msg);
		return false;
		}
		t=new chinapay.SecureLink (key);
		// 对一段字符串的签名验证
		flag1 = t. verifyAuthToken (plainData, ChkValue2) ; // ChkValue2为ChinaPay应答传回的域段
		
		return flag1;
	}
	
	/** 
	 * unicode转中文
	 * @Title: unicodeToGB 
	 * @Description: unicode转中文
	 * @param str
	 * @return
	 */
	public static String unicodeToGB(String str) {
		if(str==null||str.equals(null)){
			return "";
		}else{
			StringBuffer sb = new StringBuffer();
			StringTokenizer st = new StringTokenizer(str, "\\u");
			while (st.hasMoreTokens()) {
				sb.append((char) Integer.parseInt(st.nextToken(), 16));
			}
			return sb.toString();
		}
	}
	
	/** 
	 * 中文转unicode
	 * @Title: toUnicodeString 
	 * @Description: 中文转unicode
	 * @param str
	 * @return
	 */
	public static String toUnicodeString(String str) {
		StringBuffer sb = new StringBuffer();
		
		if(StringUtils.isEmpty(str)){
		    return "";
		}
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				sb.append("\\u" + Integer.toHexString(c));
			}
		}
		return sb.toString();
	}
	
	/**
	 * 
	 * 金额格式化，单位为分
	 * @Title: formatPayNum 
	 * @Description: 金额格式化，单位为分
	 * @param amt
	 * @return
	 */
	private static final DecimalFormat amtFormat = new DecimalFormat("#.00");
	public static String formatPayNum(String amt){
		amt = amtFormat.format(Double.valueOf(amt)).replace(".", "");
		return amt;
	}
	
	
	/**
	 * 
	 * POST提交
	 * @Title: transport 
	 * @Description: TODO
	 * @param url
	 * @param message
	 * @return
	 */
	public static String postData (String url, String message){
		StringBuffer sb = new StringBuffer();
		try {
			URL urls = new URL(url);
			HttpURLConnection uc = (HttpURLConnection) urls.openConnection();
			uc.setRequestMethod("POST");
			uc.setRequestProperty("content-type",
					"application/x-www-form-urlencoded");
			uc.setRequestProperty("charset", "GBK");
			uc.setDoOutput(true);
			uc.setDoInput(true);
			uc.setReadTimeout(30000);
			uc.setConnectTimeout(30000);
			OutputStream os = uc.getOutputStream();
			DataOutputStream dos = new DataOutputStream(os);
			dos.write(message.getBytes("utf-8"));
			dos.flush();
			os.close();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					uc.getInputStream(), "UTF-8"));
			String readLine = "";
			while ((readLine = in.readLine()) != null) {
				sb.append(readLine);
			}
			in.close();
		} catch (Exception e) {
			e.getMessage();
		}
		return sb.toString();
	}
	
	/**
	 * 
	 * 解析格式为"a=xx&b=xxx"的数据到map
	 * @Title: analyRespose 
	 * @Description: 解析格式为"a=xx&b=xxx"的数据到map
	 * @param str
	 * @return
	 */
	public static Map<String,String> analyRespose(String str){
//		Map<String,String> m = new HashMap<String, String>();
		Map<String,String> map = new HashMap<String, String>();
		//分割字符串
		String ss[] = str.split("&");
		
		for(int i =0; i<ss.length; i++){
			map.put(ss[i].substring(0,ss[i].indexOf("=")),ss[i].substring(ss[i].indexOf("=")+1));
		}
		return map;
	}
	
}
